import { Interceptors } from './interceptors';
export class HttpRequest {
  public axios: any
  constructor() {
    // 获取axios实例
    this.axios = new Interceptors().getInterceptors();
  }
  public get(url: string, params: String, config: Object = {}) {
    return new Promise((resolve, reject) => {
      let paramUrl = url
      if (params) {
        paramUrl += `?${params}`
      }
      this.axios.get(paramUrl, {
        ...config
      }).then((res: any) => {
        this.resultHandle(res, resolve, reject, url);
      }).catch((err: { message: any; }) => {
        console.log(err)
        reject(err.message);
      })
    })
  }

  public post(url: string, params: Object, config: Object = {}) {
    return new Promise((resolve, reject) => {
      this.axios.post(url, params, {
        ...config   //  导出添加的下载类型
      }).then((res: any) => {
        this.resultHandle(res, resolve, reject, url);
      }).catch((err: { message: any; }) => {
        reject(err.message);
      })
    })
  }

  public delete(url: string, params: String, config: Object = {}) {
    return new Promise((resolve, reject) => {
      let paramUrl = url
      if (params) {
        paramUrl += `?${params}`
      }
      this.axios.delete(paramUrl, {
        ...config
      }).then((res: any) => {
        this.resultHandle(res, resolve, reject, url);
      }).catch((err: { message: any; }) => {
        console.log(err)
        reject(err.message);
      })
    })
  }
  public put(url: string, params: Object, config: Object = {}) {
    return new Promise((resolve, reject) => {
      this.axios.put(url, params, {
        ...config   //  导出添加的下载类型
      }).then((res: any) => {
        this.resultHandle(res, resolve, reject, url);
      }).catch((err: { message: any; }) => {
        reject(err.message);
      })
    })
  }


  public resultHandle(res: any, resolve: { (value: unknown): void; (value: unknown): void; (arg0: any): void; },reject: { (value: unknown): void; (value: unknown): void; (arg0: any): void; }, url: string) {
    if (res) {
      if (res.code === 200 || (res.size > 0 && res.type)) {   //  增加blob文件判断
        resolve(res);
      } else {
        resolve(res);
        // this.errorHandle(res, reject, url);
      }
    }
  }
  public errorHandle(res: any, reject: any, url: string) {
    console.error('错误接口：' + url)
    if (res.hasOwnProperty('message')) {
      // ElMessage.warning(res.message);  // 统一谈服务端提示,我们提示统一由服务端提供
    } else if (res.hasOwnProperty('msg')) {
      // ElMessage.warning(res.msg);  // 统一谈服务端提示,我们提示统一由服务端提供
    }
    // 状态码判断
    if (res) {
      switch (res.code) {
        case -102:
          break;
        case -152:
          break;
        default:
          reject(res);
      }
    }
  }
}

export default HttpRequest
